//
//  ZYCLectureRecordsListViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/8/9.
//

#import "ZYCLectureRecordsListViewController.h"
#import <FSCalendar.h>
#import "ZYCLectureRecordStatisticsViewController.h"
#import "ZYCScheduleRootCell.h"
#import "ZYCScheduleRootSectionHeaderView.h"
#import "ZYCLectureRecordsModel.h"
#import "ZYCLectureRecordHandleExceptionViewController.h"
#import "ZYCLectureRecordCell.h"
#import "UIImage+imgaeWithColor.h"
#import "BTImageTitleButton.h"
#import "ZYCNoDataView.h"
#import "LunarFormatter.h"
#import "ZYCCalendarCell.h"

@interface ZYCLectureRecordsListViewController ()<FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance,UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,ZYCScheduleRootCellDelegate>
{
    void * _KVOContext;
}
@property (nonatomic, strong) FSCalendar *calendar;
@property (nonatomic, strong) LunarFormatter *lunarFormatter;
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UIImageView *calendaerImgView;
@property (nonatomic, strong) NSCalendar *gregorian;
@property (nonatomic, strong) BTImageTitleButton *statisticsButton;
@property (nonatomic, strong) UIButton *previousButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UIPanGestureRecognizer *scopeGesture;
@property (nonatomic, strong) MASConstraint *calenderHeightConstraint;

@property (nonatomic, copy) NSString *checkDate;
@property (nonatomic, strong) NSArray *normalArr;
@property (nonatomic, strong) NSArray *exceptArr;
@property (nonatomic, strong) ZYCNoDataView *noDataView;
@end

@implementation ZYCLectureRecordsListViewController


#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"授课记录";
    self.gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    self.lunarFormatter = [[LunarFormatter alloc] init];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.statisticsButton];

    [self setupContaints];
    [self addPanGestureRecognizer];
    self.checkDate = [self getCurrentTime];
    [self loadCureentMonthLectureRecords];

    // 监听KVO
    [self.calendar addObserver:self forKeyPath:@"scope" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:_KVOContext];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadCureentDayLectureRecordsWithTime:self.checkDate];
}

#pragma mark - ZYCScheduleRootCellDelegate
// 处理异常
- (void)scheduleRootCellDidDealExceptWithModel:(ZYCLectureRecordsModel *)model{
    if ([model.isObjection integerValue] == 0) {
        ZYCLectureRecordHandleExceptionViewController *vc = [ZYCLectureRecordHandleExceptionViewController new];
        vc.checkId = model.checkId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark - FSCalendarDataSource && FSCalendarDelegate

- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated
{
    [self.calenderHeightConstraint uninstall];
    [self.calendar mas_updateConstraints:^(MASConstraintMaker *make) {
        self.calenderHeightConstraint = make.height.mas_equalTo(CGRectGetHeight(bounds));
    }];
}


- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date{
    if ([self.gregorian isDateInToday:date]) {
        return @"今";
    }
    return nil;
}
- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date{
    return [self.lunarFormatter stringFromDate:date];
}

- (FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{

    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.normalArr containsObject:dateString]) {
        ZYCCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
        cell.statusLabel.textColor = HEX_RGB(@"#41B166");
        cell.statusLabel.text = @"正常";
        return cell;
    }
    if ([self.exceptArr containsObject:dateString]) {
        ZYCCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
        cell.statusLabel.textColor = HEX_RGB(@"#EC4402");
        cell.statusLabel.text = @"异常";
        return cell;
    }
    return nil;
}
- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.normalArr containsObject:dateString]) {
        return 1;
    }
    if ([self.exceptArr containsObject:dateString]) {
        return 1;
    }else{
        return 0;
    }
}

- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance fillDefaultColorForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([dateString isEqualToString:[self.dateFormatter stringFromDate:[NSDate date]]]) {
        return [UIColor blackColor];
    }
    if ([self.normalArr containsObject:dateString]) {
        return HEX_RGB(@"#219D51");
    }else if ([self.exceptArr containsObject:dateString]) {
        return HEX_RGB(@"#E93C06");
    }else{
        return nil;
    }
}


// 切换日期
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
//    NSLog(@"did select %@",[self.dateFormatter stringFromDate:date]);
    NSString *timeStr = [self.dateFormatter stringFromDate:date];
    [self loadCureentDayLectureRecordsWithTime:timeStr];
    
}
- (void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
//    NSLog(@"did deSelect %@",[self.dateFormatter stringFromDate:date]);
}

// 切换月份
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    NSString *dateString = [self.dateFormatter stringFromDate:calendar.currentPage];
    self.checkDate = dateString;
    [self loadCureentMonthLectureRecords];
}


#pragma mark - 网络请求
//当前月的授课记录
- (void)loadCureentMonthLectureRecords{
    NSDictionary *params = @{
        @"checkDate":self.checkDate,
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_LectureRecord requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            self.normalArr = responseObject[@"body"][@"iosnomal"];
            self.exceptArr = responseObject[@"body"][@"iosexcept"];

            [self.calendar reloadData];
            
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


- (void)loadCureentDayLectureRecordsWithTime:(NSString *)timeStr{
    NSDictionary *params = @{
        @"checkDate":timeStr,
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_QueryReportByDay requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCLectureRecordsModel class] json:responseObject[@"body"]];
                [self.dataSource removeAllObjects];
                [self.dataSource addObjectsFromArray:array];
                if (self.dataSource.count == 0) {
                    self.noDataView.hidden = NO;
                    self.tableView.hidden = YES;
                }else{
                    self.noDataView.hidden = YES;
                    self.tableView.hidden = NO;
                }
                [self.tableView reloadData];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}



#pragma mark - private method
- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

- (void)setupContaints{
    [self.view addSubview:self.bgImageView];
    [self.view insertSubview:self.bgImageView atIndex:0];
    [self.view addSubview:self.calendaerImgView];
    [self.view addSubview:self.calendar];
    [self.calendar addSubview:self.previousButton];
    [self.calendar addSubview:self.nextButton];
    [self.view addSubview:self.tableView];
    
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(kNavBarAndStatusBarHeight);
        make.height.mas_equalTo(138.0f);
    }];

    [self.calendaerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(kNavBarAndStatusBarHeight);
        make.height.mas_equalTo(27.0f);
    }];
    
    [self.calendar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10.0f);
        make.right.equalTo(self.view).offset(-10.0f);
        make.top.equalTo(self.calendaerImgView.mas_centerY);
        self.calenderHeightConstraint = make.height.mas_equalTo(282);
    }];

    [self.previousButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.calendar).offset(95.0f);
        make.centerY.equalTo(self.calendar.mas_top).offset(27.0f);
        make.size.mas_equalTo(CGSizeMake(10, 8.5));
    }];

    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.calendar).offset(-95.0f);
        make.centerY.equalTo(self.calendar.mas_top).offset(27.0f);
        make.size.mas_equalTo(CGSizeMake(10, 8.5));
    }];


    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.calendar.mas_bottom);
    }];
}

- (void)addPanGestureRecognizer{
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.calendar action:@selector(handleScopeGesture:)];
    panGesture.delegate = self;
    panGesture.minimumNumberOfTouches = 1;
    panGesture.maximumNumberOfTouches = 2;
    [self.view addGestureRecognizer:panGesture];
    self.scopeGesture = panGesture;
    // While the scope gesture begin, the pan gesture of tableView should cancel.
    [self.tableView.panGestureRecognizer requireGestureRecognizerToFail:panGesture];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCScheduleRootCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCScheduleRootCell class]) forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.section];
    [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
    cell.delegate = self;
    return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 37.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 76.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ZYCScheduleRootSectionHeaderView *headerView = [[ZYCScheduleRootSectionHeaderView alloc] init];
    ZYCLectureRecordsModel *model = self.dataSource[section];
    headerView.status = model.classStatus;
    return headerView;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}


#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if (context == _KVOContext) {
        FSCalendarScope oldScope = [change[NSKeyValueChangeOldKey] unsignedIntegerValue];
        FSCalendarScope newScope = [change[NSKeyValueChangeNewKey] unsignedIntegerValue];
//        NSLog(@"From %@ to %@",(oldScope==FSCalendarScopeWeek?@"week":@"month"),(newScope==FSCalendarScopeWeek?@"week":@"month"));
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - getters
- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ty"]];
    }
    return _bgImageView;
}

- (UIImageView *)calendaerImgView {
    if (!_calendaerImgView) {
        _calendaerImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rili"]];
    }
    return _calendaerImgView;
}


- (FSCalendar *)calendar {
    if (!_calendar) {
        _calendar = [[FSCalendar alloc] init];
        _calendar.delegate = self;
        _calendar.dataSource = self;
        _calendar.headerHeight = 50.0f;
        _calendar.appearance.headerMinimumDissolvedAlpha = 0;
        _calendar.backgroundColor = [UIColor whiteColor];
        _calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        _calendar.placeholderType = FSCalendarPlaceholderTypeNone; //只显示当前月份
        _calendar.appearance.headerDateFormat = @"yyyy年MM月";// 设置头部时间格式
        _calendar.appearance.weekdayTextColor = HEX_RGB(@"#62676A");//设置周字体颜色
        _calendar.appearance.headerTitleColor = HEX_RGB(@"#262A28");//设置头字体颜色
        _calendar.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase|FSCalendarCaseOptionsWeekdayUsesSingleUpperCase;
        //        _calendar.appearance.eventDefaultColor = HEX_RGB(@"#CECECE");// 设置日期下的小点点颜色
        _calendar.appearance.selectionColor = FSCalendarStandardTodayColor; // 设置点击某日某日的颜色
        _calendar.appearance.todayColor = FSCalendarStandardTodayColor;// 设置今天颜色
        [_calendar registerClass:[ZYCCalendarCell class] forCellReuseIdentifier:@"cell"];
    }
    return _calendar;
}

- (UIButton *)previousButton {
    if (!_previousButton) {
        _previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_previousButton setImage:[UIImage imageNamed:@"zuo"] forState:UIControlStateNormal];
        [_previousButton addTarget:self action:@selector(previousClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _previousButton;
}

- (UIButton *)nextButton {
    if (!_nextButton) {
        _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton setImage:[UIImage imageNamed:@"you"] forState:UIControlStateNormal];
        [_nextButton addTarget:self action:@selector(nextClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextButton;
}

- (BTImageTitleButton *)statisticsButton {
    if (!_statisticsButton) {
        _statisticsButton = [BTImageTitleButton buttonWithType:UIButtonTypeCustom];
        [_statisticsButton setTitle:@"统计" forState:UIControlStateNormal];
        [_statisticsButton setImage:[UIImage imageNamed:@"tj"] forState:UIControlStateNormal];
        _statisticsButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_statisticsButton addTarget:self action:@selector(clickStatistics:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _statisticsButton;
}
- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}


- (void)clickStatistics:(UIButton *)sender{
    ZYCLectureRecordStatisticsViewController *vc = [ZYCLectureRecordStatisticsViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCScheduleRootCell class] forCellReuseIdentifier:NSStringFromClass([ZYCScheduleRootCell class])];
    }
    return _tableView;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}
- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}


- (NSArray *)normalArr {
    if (!_normalArr) {
        _normalArr = [[NSArray alloc] init];
    }
    return _normalArr;
}

- (NSArray *)exceptArr {
    if (!_exceptArr) {
        _exceptArr = [[NSArray alloc] init];
    }
    return _exceptArr;
}


#pragma mark - action
-(void)previousClicked:(UIButton *)sender{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:previousMonth animated:YES];
}

-(void)nextClicked:(UIButton *)sender{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:nextMonth animated:YES];
}

#pragma mark - UIGestureRecognizerDelegate

// Whether scope gesture should begin
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    BOOL shouldBegin = self.tableView.contentOffset.y <= -self.tableView.contentInset.top;
    if (shouldBegin) {
        CGPoint velocity = [self.scopeGesture velocityInView:self.view];
        switch (self.calendar.scope) {
            case FSCalendarScopeMonth:
                return velocity.y < 0;
            case FSCalendarScopeWeek:
                return velocity.y > 0;
        }
    }
    return shouldBegin;
}

- (void)dealloc{
    [self.calendar removeObserver:self forKeyPath:@"scope" context:_KVOContext];
    NSLog(@"%s",__FUNCTION__);
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
